﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EraNet.Core;
using EraNet.Core.Caching;
using EraNet.Core.Data;
using EraNet.Core.Events;
using EraNet.Core.Model.SysManage;
using EraNet.Core.Model.Account;
using EraNet.Common;
using EraNet.Common.Files;
//using EraNet.Data;
using System.Data;
//using System.Data.Entity;

namespace EraNet.Services.Account
{
    public partial class MemberService : IMemberService
    {
        #region Constants
        private const string MEMBER_BY_ID_KEY = "Era.Member.id-{0}";
        private const string MEMBER_PATTERN_KEY = "Era.Member.";
        #endregion

        #region Fields
        private readonly IRepository<Member> _memberRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
        private readonly IRepository<CardAllotLogs> _cardAllotLogsRepository;
        private readonly IRepository<MemberAdj> _memberadjRepository;
        private readonly IRepository<SysCards> _syscardsRepository;
        //private readonly IDbContext _context;
        #endregion

        #region Ctor
        public MemberService(IRepository<Member> memberRepository, ICacheManager cacheManager, IEventPublisher eventPublisher, IRepository<CardAllotLogs> cardAllotLogsRepository, IRepository<MemberAdj> memberadjRepository
            , IRepository<SysCards> syscardsRepository)
        {
            _memberRepository = memberRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
            _cardAllotLogsRepository = cardAllotLogsRepository;
            _memberadjRepository = memberadjRepository;
            _syscardsRepository = syscardsRepository;
        }
        #endregion

        #region Methods
        /// <summary>
        /// 插入新学员
        /// </summary>
        /// <param name="model">信息类，默认情况下，会采用用户的身份证作为用户名和密码</param>
        /// <returns>0->失败  1-〉成功 2-〉用户存在或者身份证存在  5-〉用户名格式错误</returns>
        public int InsertMember(Member model)
        {
            int rs = 0;
            if (model == null)
                throw new ArgumentNullException("Member");
            //错误的用户名
            if (!Common.Validator.IsUserName(model.AccountName)) return 6; //用户已存在

            var m = _memberRepository.Table.Where(c => (c.AccountName == model.AccountName || c.IDCard == model.IDCard) && c.SchoolID == model.SchoolID).FirstOrDefault();
            if (m != null) return 7;
            if (_memberRepository.Insert(model) > 0) rs = 8;
            return rs;
        }

        /// <summary>
        /// 用户注册  生成新的学员并在卡片分配记录表插入相关联的信息
        /// </summary>
        /// <param name="model">信息类，默认情况下，会采用用户的身份证作为用户名和密码</param>
        /// <returns>0->失败  1-〉成功 2-〉用户存在或者身份证存在  5-〉用户名格式错误</returns>
        public int RegisterMember(Member model, SysCards card, int SchoolId, bool isSchool)
        {
            int rs = 0;
            if (model == null)
                throw new ArgumentNullException("Member");
            //错误的用户名
            if (!Common.Validator.IsUserName(model.AccountName)) return 6; //用户已存在

            var m = _memberRepository.Table.Where(c => c.AccountName == model.AccountName && c.IDCard == model.IDCard && c.SchoolID == SchoolId).FirstOrDefault();
            if (m != null) return 7;

            //分配记录
            var logs = new CardAllotLogs();
            logs.CardId = card.Id;
            logs.CardNo = card.Markstr + card.CardNo.ToString();
            logs.CardPwd = card.CardPassword;
            logs.CreatedOnUtc = DateTime.Now;

            if (_memberRepository.Insert(model) > 0)
            {
                logs.MemberId = model.Id;
                if (_cardAllotLogsRepository.Insert(logs) > 0)
                {
                    SysCards cardinfo = _syscardsRepository.GetById(card.Id);
                    if (isSchool)
                    {
                        cardinfo.SchoolId = SchoolId;
                    }
                    cardinfo.IsValid = false;
                    _syscardsRepository.Update(cardinfo);
                    rs = 8;
                }
                else
                    rs = 8;
            }
            else
            {
                rs = 8;
            }

            return rs;
        }


        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>0-〉删除失败 1-〉删除成功 2-〉不存在该用户</returns>
        public int DeleteMember(int userId)
        {
            var m = _memberRepository.GetById(userId);
            if (m == null) return 2;
            if (_memberRepository.Delete(m) > 0)
            {
                _cacheManager.RemoveByPattern(MEMBER_PATTERN_KEY);

                //event notification
                _eventPublisher.EntityDeleted(m);
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="Member">用户实体</param>
        /// <returns>0-〉更新失败 1-〉更新成功</returns>
        public int UpdateMember(Member member)
        {
            if (member == null)
                throw new ArgumentNullException("category");

            if (_memberRepository.Update(member) > 0)
            {

                //cache
                _cacheManager.RemoveByPattern(MEMBER_PATTERN_KEY);

                //event notification
                _eventPublisher.EntityUpdated(member);
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 根据用户ID获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Member GetMemberById(int userId)
        {
            if (userId <= 0)
                return null;

            string key = string.Format(MEMBER_BY_ID_KEY, userId);
            return _cacheManager.Get(key, () =>
            {
                var pv = _memberRepository.GetById(userId);
                return pv;
            });
        }

        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public Member GetMemberByName(string userName)
        {
            if (string.IsNullOrEmpty(userName))
                return null;

            var m = _memberRepository.Table.Where(c => c.AccountName == userName).FirstOrDefault();
            //不存在
            if (m == null) return null;

            string key = string.Format(MEMBER_BY_ID_KEY, m.Id);
            return _cacheManager.Get(key, () =>
            {
                var pv = m;
                return pv;
            });
        }

        /// <summary>
        /// 根据用户名获取用户 模糊查询
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public List<Member> GetLikeMemberByName(string userName,int schoolId)
        {
            if (string.IsNullOrEmpty(userName))
                return null;

            var m = _memberRepository.Table.Where(c => c.Names.Contains(userName) && c.SchoolID == schoolId).ToList();
            //不存在
            if (m == null) return null;

            return m;
        }

        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public Member GetMemberByName(string userName,int schoolId)
        {
            if (string.IsNullOrEmpty(userName))
                return null;

            var m = _memberRepository.Table.Where(c => c.AccountName == userName && c.SchoolID == schoolId).FirstOrDefault();
            //不存在
            if (m == null) return null;

            string key = string.Format(MEMBER_BY_ID_KEY, m.Id);
            return _cacheManager.Get(key, () =>
            {
                var pv = m;
                return pv;
            });
        }


        /// <summary>
        /// 根据身份证获取用户
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public Member GetMemberByIdCard(string IdCard, int schoolId)
        {
            if (string.IsNullOrEmpty(IdCard))
                return null;

            var m = _memberRepository.Table.Where(c => c.IDCard == IdCard&& c.SchoolID==schoolId).FirstOrDefault();
            //不存在
            if (m == null) return null;

            string key = string.Format(MEMBER_BY_ID_KEY, m.Id);
            return _cacheManager.Get(key, () =>
            {
                var pv = m;
                return pv;
            });
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="Password"></param>
        /// <returns>0-〉登陆失败  5.登陆成功  6->用户名不存在 7-〉用户密码错误 8->用户名为空或者格式错误  9->密码为空或者格式错误 10-〉用户被锁定或者过期</returns>
        public Member GetMember(string userName, string password, out int result)
        {
            result = 0;
            #region 数据检测
            if (string.IsNullOrEmpty(userName) || !Common.Validator.IsUserName(userName))
            {
                result = 8;
                return null;
            }
            if (string.IsNullOrEmpty(password))
            {
                result = 9;
                return null;
            }
            #endregion
            var m = GetMemberByName(userName);
            if (m == null)
            {
                result = 6;
            }
            else
            {
                string pwd = Utility.MD5(password);
                //string pwd = password;
                //密码错误
                if (m.Password != pwd)
                {
                    result = 7;
                    return null;
                }
                if (m.Status != 1)
                {
                    result = 10;
                    return null;
                }
                //登录成功 更新登录IP地址以及登录时间
                m.LastIPAddress = Common.Request.GetIP();
                m.LastLoginDate = DateTime.Now;
                UpdateMember(m);

                result = 5;
            }

            return m;
        }


        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="Password"></param>
        /// <returns>0-〉登陆失败  5.登陆成功  6->用户名不存在 7-〉用户密码错误 8->用户名为空或者格式错误  9->密码为空或者格式错误 10-〉用户被锁定或者过期</returns>
        public Member GetMemberByCard(string userName, string password, string salt, out int result)
        {
            result = 0;
            #region 数据检测
            if (string.IsNullOrEmpty(userName) || !Common.Validator.IsUserName(userName))
            {
                result = 8;
                return null;
            }
            if (string.IsNullOrEmpty(password))
            {
                result = 9;
                return null;
            }
            #endregion
            var m = GetMemberByName(userName);
            if (m == null)
            {
                result = 6;
            }
            else
            {
                string pwd = Utility.MD5(salt + password);
                //密码错误
                if (m.Password != pwd)
                {
                    result = 7;
                    return null;
                }
                if (m.Status != 1)
                {
                    result = 10;
                    return null;
                }
                //登录成功 更新登录IP地址以及登录时间
                m.LastIPAddress = Common.Request.GetIP();
                m.LastLoginDate = DateTime.Now;
                UpdateMember(m);

                result = 5;
            }

            return m;
        }


        ///// <summary>
        ///// 根据卡片信息，获取用户信息
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //public Member GetMemberByCard(int  cardId)
        //{
        //    if (cardId <= 0) 
        //        return null;
        //    var m=_memberRepository.Table.Where(c=>c.
        //}

        public IPagedList<Member> GetAllMember(DateTime? regTime, DateTime? endTime, int pageSize, int pageIndex, bool showHidden = false)
        {
            var query = _memberRepository.Table;
            if (regTime.HasValue)
                query = query.Where(b => regTime.Value <= b.CreateDate);
            if (endTime.HasValue)
                query = query.Where(b => endTime.Value >= b.CreateDate);

            if (!showHidden)
            {
                query = query.Where(b => b.Status == 1);
            }
            query = query.OrderByDescending(b => b.CreateDate);

            var member = new PagedList<Member>(query, pageIndex, pageSize);
            return member;
        }

        public IPagedList<Member> GetMemberBySchool(DateTime? regTime, DateTime? endTime, int schoolId, int pageSize, int pageIndex, bool showHidden = false)
        {
            var query = _memberRepository.Table;
            if (regTime.HasValue)
                query = query.Where(b => regTime.Value <= b.CreateDate);
            if (endTime.HasValue)
                query = query.Where(b => endTime.Value >= b.CreateDate);

            if (!showHidden)
            {
                query = query.Where(b => b.Status == 1);
            }
            query = query.Where(b => b.SchoolID == schoolId);
            query = query.OrderByDescending(b => b.CreateDate);

            var member = new PagedList<Member>(query, pageIndex, pageSize);
            return member;
        }

        public IPagedList<Member> GetMemberBySchool(int schoolId, int pageSize, int pageIndex, bool showHidden = false)
        {
            var query = _memberRepository.Table;
            if (!showHidden)
            {
                query = query.Where(b => b.Status == 1);
            }
            query = query.Where(b => b.SchoolID == schoolId);
            query = query.OrderByDescending(b => b.CreateDate);

            var member = new PagedList<Member>(query, pageIndex, pageSize);
            return member;
        }

        /// <summary>
        /// 获取登录学员实体
        /// </summary>
        /// <returns></returns>
        public Member GetLoginMember()
        {
            Member dsa = null;
            Object obj = null;
            if (Utility.GetCookie("MemberModel") != null && Utility.GetCookie("MemberModel") != "")
                obj = (Member)SerializationHelper.BtyDeSerializer(Utility.GetCookie("MemberModel"));
            if (obj != null) dsa = (Member)obj;
            return dsa;
        }


        public int UpdateMemberAdj(MemberAdj model)
        {
            if (model == null)
                throw new ArgumentNullException("null MemberAdj model");

            return _memberadjRepository.Update(model) > 0 ? 1 : 0;
        }

        public MemberAdj GetMemberAdjById(int memberId)
        {
            if (memberId <= 0) return null;
            return _memberadjRepository.Table.Where(c => c.MemberId == memberId).FirstOrDefault();
        }

        ///// <summary>
        ///// 修改实体 不需要再次查询
        ///// </summary>
        ///// <param name="member"></param>
        ///// <returns></returns>
        //public int MyUpdate(Member member)
        //{
        //    var dataSettingsManager = new DataSettingsManager();
        //    var dataProviderSettings = dataSettingsManager.LoadSettings();
        //    EraObjectContext dbContext = new EraObjectContext(dataProviderSettings.DataConnectionString);
        //    dbContext.Entry(member).State = EntityState.Modified;
        //    return dbContext.SaveChanges();
        //}

        #endregion
    }
}
